
module Routes
  class DefaultRouter
    
    def initialize(config_file)
      @hosts = []
      @default = nil
  
      config_file ||= "config/routes.yml"

      if File.exists?(config_file)
        YAML.load_file( config_file ).each do |name,config|
          unless name == "default"
            config[:name] = name
            @hosts << config.symbolize_keys
          else
            @default = config.symbolize_keys
          end
        end
      else
        @default = {:host => "localhost", :port => "3000"}
      end

      $logger.debug "Default hosts => #{@default.inspect}"
      $logger.debug "Application hosts => #{@hosts.inspect}"
    end

    def route_for_uri(request_uri)
      configuration(request_uri)
    end

    def configuration( request_uri )
      # locate the first entry to match the given uri
      conf = @hosts.find do |c|
        Regexp.new(c[:match_url]).match(request_uri)
      end
      conf = @default unless conf
      conf
    end
  end
end
